# Copyright (c) Mengning Software. 2023. All rights reserved.
#
# Super IDE licensed under GNU Affero General Public License v3 (AGPL-3.0) .
# You can use this software according to the terms and conditions of the AGPL-3.0.
# You may obtain a copy of AGPL-3.0 at:
#
#    https://www.gnu.org/licenses/agpl-3.0.txt
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the AGPL-3.0 for more details.

import logging
import multiprocessing

import requests

HTTP_HOST = "127.0.0.1"
HTTP_PORT_BEGIN = 8008
HTTP_PORT_END = 8050

log = logging.getLogger(__name__)


def _shutdown():
    for port in range(HTTP_PORT_BEGIN, HTTP_PORT_END):
        try:
            requests.get(
                "http://%s:%d?__shutdown__=1" % (HTTP_HOST, port), timeout=(0.5, 2)
            )
            log.debug("The server %s:%d is stopped", HTTP_HOST, port)
        except:  # pylint:disable=bare-except
            pass


def shutdown_pio_home_servers():
    proc = multiprocessing.Process(target=_shutdown)
    proc.start()
    proc.join(10)
    proc.terminate()
    return True
